package com.sz.web.context;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WEB上下文容器
 *
 * @author: yxl
 * 2025-07-23
 */
public class SzWebContext {
    private final HttpServletRequest request;
    private final HttpServletResponse response;
    private final RequestType requestType;
    private final byte[] cachedBody;
    private final Map<String, Object> attributes = new ConcurrentHashMap<>();

    public SzWebContext(HttpServletRequest request, HttpServletResponse response, RequestType requestType, byte[] cacheBody) {
        this.request = Objects.requireNonNull(request);
        this.response = Objects.requireNonNull(response);
        this.requestType = requestType != null ? requestType : RequestType.OUTER;
        this.cachedBody = cacheBody != null ? cacheBody : new byte[0];
    }

    // 基础访问方法
    protected HttpServletRequest getRequest() {
        return request;
    }

    protected HttpServletResponse getResponse() {
        return response;
    }

    // 属性存取
    protected void setAttribute(String key, Object value) {
        attributes.put(key, value);
    }

    protected Object getAttribute(String key) {
        return attributes.get(key);
    }

    // 实用方法（保持最小集）
    protected String getHeader(String name) {
        return request.getHeader(name);
    }

    protected byte[] getCachedBody() {
        return cachedBody;
    }

    protected RequestType getRequestType() {
        return requestType;
    }

    protected String getRequestBody() {
        return new String(cachedBody, StandardCharsets.UTF_8);
    }

    public enum RequestType {
        OUTER, // 外部请求（前端请求）
        INNER; // 内部请求（内部服务调用）

        public static RequestType getByName(String name) {
            for (RequestType value : values()) {
                if (value.name().equals(name.toUpperCase())) {
                    return value;
                }
            }
            return null;
        }
    }

}
